package com.mlk.rbac.Service.impl;

import java.util.Date;
import java.util.Objects;

import javax.annotation.Resource;

import com.mlk.core.component.page.Page;
import com.mlk.core.component.page.Pager;
import com.mlk.core.config.UserConfig;
import com.mlk.core.constants.Constant;
import com.mlk.core.util.JSONUtils;
import com.mlk.core.util.MD5Utils;
import com.mlk.core.util.ServerResponse;
import com.mlk.core.util.SessionUtils;
import com.mlk.rbac.Service.SysUserService;
import com.mlk.rbac.constant.RBACConstant;
import com.mlk.rbac.dto.SysUserDTO;
import com.mlk.rbac.mapper.SysUserMapper;
import com.mlk.rbac.param.SysUserParam;
import com.mlk.rbac.po.SysUser;
import com.mlk.rbac.query.SysUserQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 系统用户服务
 * 
 * @author trek
 */
@Service
public class SysUserServiceImpl implements SysUserService {

	@Resource
	private SysUserMapper sysUserMapper;

	@Autowired
	private RedisTemplate<String,String> redisTemplate;

	@Override
    @Transactional
	public ServerResponse userAdd(SysUserParam user) {
		// 检查用户名是否有相同的
		if (existsUsername(user.getUsername())) {
			return ServerResponse.fail("已经存在相同的用户名的用户了");
		}

		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(user, sysUser);
		// 添加一些必要的属性
		sysUser.setPassword(MD5Utils.encode(sysUser.getPassword()));
		sysUser.setStatus(Constant.UserStatus.ok);
		sysUser.setOperator(SessionUtils.getSysUser().getName());
		sysUser.setOperateTime(new Date());

		int count = this.sysUserMapper.insert(sysUser);
		if (count == 0) {
			return ServerResponse.fail("添加用户失败");
		}

		// 刷入缓存信息
        this.redisTemplate.opsForValue().set(UserConfig.CACHE_PREFIX+sysUser.getId(), JSONUtils.toJSONString(sysUser));

		return ServerResponse.ok("添加用户成功");
	}

	/**
	 * 判断是否有相同的用户名
	 * 
	 * @param username
	 * @return
	 */
	private boolean existsUsername(String username) {
		return this.sysUserMapper
				.selectCount(new EntityWrapper<SysUser>(SysUser.builder().username(username).build())) != 0;
	}

	@Override
	@Transactional
	public ServerResponse userDelete(Integer id) {

		if (id == null) {
			return ServerResponse.fail("删除或冻结的用户不存在");
		}

		// 删除(冻结用户)
		int count = this.sysUserMapper
				.updateById(SysUser.builder().id(id).status(Constant.UserStatus.lock).build());
		if (count == 0) {
			return ServerResponse.fail("删除或冻结用户失败");
		}
		// 删除缓存之中的信息
        this.redisTemplate.delete(UserConfig.CACHE_PREFIX+id);

		return ServerResponse.ok("删除用户成功");
	}

	@Override
	@Transactional
	public ServerResponse updateUser(SysUserParam user) {

		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(user, sysUser);
		// 设置操作人
		sysUser.setOperateTime(new Date());
		sysUser.setOperator(SessionUtils.getSysUser().getName());

		int count = this.sysUserMapper.updateById(sysUser);
		if (count == 0) {
			return ServerResponse.fail("系统用户更新失败");
		}

		// 刷新缓存的信息
        SysUser newUser = this.sysUserMapper.selectById(user.getId());
		this.redisTemplate.opsForValue().set(UserConfig.CACHE_PREFIX+newUser.getId(),JSONUtils.toJSONString(newUser));

        return ServerResponse.ok("系统用户更新成功");
	}

	@Override
	@Page
	public Pager<SysUserDTO> userList(SysUserQuery userQuery) {

		return Pager.adapt(this.sysUserMapper.userList(userQuery));
	}

	@Override
	public ServerResponse onOrOff(Integer id) {
		if (id == null) {
			return ServerResponse.fail("更新的id不能为空");
		}

		SysUser user = this.sysUserMapper.selectById(id);
		if (user == null) {
			return ServerResponse.fail("更新的用户的id不存在");
		}
		int count = this.sysUserMapper.updateById(SysUser.builder().id(id).status(Constant.ConvertStatus(user.getStatus())).build());
		
		if(count == 0) {
			return ServerResponse.fail("更新用户的状态失败");
		}

		// 刷新缓存
        if(Objects.equals(user.getStatus(),Constant.status_ok)){
            // 直接删除缓存
            this.redisTemplate.delete(UserConfig.CACHE_PREFIX+id);
        }else{
            user.setStatus(Constant.status_ok);
            this.redisTemplate.opsForValue().set(UserConfig.CACHE_PREFIX+id,JSONUtils.toJSONString(user));
        }
		return ServerResponse.ok("更新用户的状态成功");
	}

}
